package com.yocard.yxyd.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.umeng.commonsdk.statistics.common.DeviceConfig;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yocard.yxyd.BuildConfig;
import com.yocard.yxyd.R;
import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.others.CommonTimer;
import com.yocard.yxyd.ui.activity.base.BaseActivity;
import com.yocard.yxyd.ui.contract.LoginContract;
import com.yocard.yxyd.ui.presenter.LoginPresenter;
import com.yocard.yxyd.utils.CommonUtils;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.CacheDoubleStaticUtils;
import com.yocard.yxyd.utils.util.LogUtils;
import com.yocard.yxyd.utils.util.SPUtils;
import com.yocard.yxyd.utils.util.StringUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.db.DBManager;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2019/4/1.
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {

    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.et_phone)
    AppCompatEditText etPhone;
    @BindView(R.id.et_code)
    AppCompatEditText etCode;
    @BindView(R.id.btn_login)
    TextView btnLogin;

    protected CommonTimer myTimer;
    protected boolean isRequestCode;
    protected AMapLocationClient mLocationClient;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.act_login;
    }

    private void checkLogin() {
        String token = CacheDoubleStaticUtils.getString(Constants.KEY_TOKEN);
        if (!StringUtils.isEmpty(token)) {
            ActivityUtils.startActivity(MainActivity.class);
            ActivityUtils.finishActivity(this);
        } else {
            CacheDoubleStaticUtils.remove(Constants.KEY_TOKEN);
            ActivityUtils.finishAllActivitiesExceptNewest();
        }
    }

    @Override
    protected void initEventAndData() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            ActivityUtils.finishActivity(this);
            return;
        }
//        checkLogin();
        etPhone.addTextChangedListener(textWatcher);
        etCode.addTextChangedListener(textWatcher);
        myTimer = new CommonTimer(60 * 1000, 1000, tvGetCode);
        initLocation();
        if(BuildConfig.DEBUG) {
            etCode.setText("1234");
            etPhone.setText("15196638740");
        }
    }

    @OnClick({R.id.tv_get_code, R.id.tv_protocol, R.id.btn_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_get_code:
                getSmsCode();
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_protocol:
                Bundle bundle = new Bundle();
                bundle.putString("url", Constants.PROTOCAL_USER);
                bundle.putString("title", "用户服务协议");
                ActivityUtils.startActivity(bundle, WebViewActivity.class);
                break;
        }
    }

    private void login() {
        String mobile = etPhone.getText().toString().trim();
        String code = etCode.getText().toString().trim();
        showLoadingDialog("登录中...");
        String lat = SPUtils.getInstance().getString(Constants.KEY_LATITUDE);
        String lng = SPUtils.getInstance().getString(Constants.KEY_LONGITUDE);
        String push_token = SPUtils.getInstance().getString(Constants.REGISTER_ID);
        String deviceId = getTestDeviceInfo(AppContext.getContext())[0];
        mPresenter.loginUser(mobile, code, lng, lat, deviceId, push_token);
        if(BuildConfig.DEBUG) {
            LogUtils.d("push_token = " + push_token);
        }
    }

    private void getSmsCode() {
        String phone = etPhone.getText().toString().trim();
        int phoneLength = phone.length();
        if (phoneLength == 11) {
            showLoadingDialog();
            isRequestCode = true;
            mPresenter.getCode(phone);
            tvGetCode.setEnabled(false);
        } else {
            ToastUtils.showShort("请填写正确的手机号");
        }
    }

    @Override
    public void getCodeSuccess() {
        dismisDialog();
        isRequestCode = false;
        myTimer.start();
        ToastUtils.showShort(R.string.get_sms_code_success);
    }

    @Override
    public void loginSuccess() {
        dismisDialog();
        ActivityUtils.startActivity(MainActivity.class);
        ActivityUtils.finishActivity(this);
    }

    @Override
    public void showErrorMsg(String msg) {
        super.showErrorMsg(msg);
        if (isRequestCode) {//所有接口都走这个方法，标记区别请求验证的接口
            tvGetCode.setEnabled(true);
            isRequestCode = false;
        }
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            int phoneLength = etPhone.getText().toString().trim().length();
            int codeLength = etCode.getText().toString().trim().length();
            if (phoneLength == 11) {
                etCode.requestFocus();
            }

            if (phoneLength == 11 && codeLength == 4) {
                btnLogin.setEnabled(true);
            } else {
                btnLogin.setEnabled(false);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myTimer != null) {
            myTimer.cancel();
            myTimer = null;
        }
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onBackPressed() {
        CommonUtils.doubleClickExitApp();
    }

    public static String[] getTestDeviceInfo(Context context){
        String[] deviceInfo = new String[2];
        try {
            if(context != null){
                deviceInfo[0] = DeviceConfig.getDeviceIdForGeneral(context);
                deviceInfo[1] = DeviceConfig.getMac(context);
            }
        } catch (Exception e){
        }
        return deviceInfo;
    }

    public void initLocation() {
        AndPermission.with(AppContext.getContext())
                .runtime()
                .permission(Permission.ACCESS_FINE_LOCATION)
                .onGranted(permissions -> {
                    AMapLocationClient locationClient = new AMapLocationClient(AppContext.getContext());
                    AMapLocationClientOption mOption = new AMapLocationClientOption();
                    mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                    mOption.setGpsFirst(false);
                    mOption.setNeedAddress(true);
                    mOption.setHttpTimeOut(10000);
                    mOption.setInterval(2000);
                    mOption.setOnceLocation(true);
                    locationClient.setLocationOption(mOption);
                    onLocationInit(locationClient);
                })
                .onDenied(permissions -> {
                    ToastUtils.showLong("请授予APP定位权限");
                })
                .start();
    }

    public void onLocationInit(AMapLocationClient locationClient) {
        if (mLocationClient == null) {
            mLocationClient = locationClient;
            mLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation location) {
                    String city = location.getCity();
                    SPUtils.getInstance().put(Constants.KEY_LONGITUDE, String.valueOf(location.getLongitude()));
                    SPUtils.getInstance().put(Constants.KEY_LATITUDE, String.valueOf(location.getLatitude()));

                    if (StringUtils.isEmpty(city)) {
                        ToastUtils.showLong("定位获取城市失败！");
                        return;
                    }
                }
            });
        }
        mLocationClient.startLocation();
    }

}
